/*
 * Copyright 2015-2102 Fast(http://www.cloudate.net) Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.fast.pay.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fast.pay.account.entity.RpSettRecord;
import com.fast.pay.common.core.enums.PublicEnum;
import com.fast.pay.controller.common.BaseController;
import com.fast.pay.service.CnpPayService;
import com.fast.pay.trade.exception.TradeBizException;
import com.fast.pay.trade.service.RpRemitManagerService;
import com.fast.pay.trade.service.RpTradePaymentQueryService;
import com.fast.pay.trade.utils.MerchantApiUtil;
import com.fast.pay.user.entity.RpUserPayConfig;
import com.fast.pay.user.exception.UserBizException;
import com.fast.pay.user.service.RpUserPayConfigService;
import com.fast.pay.utils.JsonUtils;

/**
 * 代付结算申请
 * @author ljf
 *
 */
@Controller
@RequestMapping(value = "/remit")
public class RemitPayController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(RemitPayController.class);


    @Autowired
    private RpRemitManagerService rpRemitManagerService;

    @Autowired
    private RpUserPayConfigService rpUserPayConfigService;

    @Autowired
    private CnpPayService cnpPayService;


    /**
     * 代付申请
     * @return
     */
    @RequestMapping("/pay")
    public Map<String, String> initPay(Model model, HttpServletRequest httpServletRequest) {
    	Map<String, String> resMap = new HashMap<String, String>();
    	resMap.put("apiCode", PublicEnum.NO.toString()); //默认失败
    	resMap.put("apiMsg", "操作失败"); //默认失败
    	Map<String, String> paramMap = new HashMap<String, String>();
        //获取商户传入参数
        String payKey = getString_UrlDecode_UTF8("payKey"); // 企业支付KEY
        paramMap.put("payKey", payKey);
        String orderNo = getString_UrlDecode_UTF8("orderNo"); // 订单编号
        paramMap.put("orderNo", orderNo);
        String remitAmout = getString_UrlDecode_UTF8("remitAmout"); // 订单金额 , 单位:元
        paramMap.put("orderAmout", remitAmout);
        String orderIp = getString_UrlDecode_UTF8("orderIp"); // 下单IP
        paramMap.put("orderIp", orderIp);
        String bankAccountName = getString_UrlDecode_UTF8("bankAccountName"); // 结算卡名字
        paramMap.put("bankAccountName", bankAccountName);
        String banAccountNo = getString_UrlDecode_UTF8("banAccountNo"); // 银行卡账号
        paramMap.put("banAccountNo", banAccountNo);
        String remark = getString_UrlDecode_UTF8("remark"); // 支付备注
        paramMap.put("remark", remark);
        String sign = getString_UrlDecode_UTF8("sign"); // 签名

        String field1 = getString_UrlDecode_UTF8("field1"); // 扩展字段1
        paramMap.put("field1", field1);
        String field2 = getString_UrlDecode_UTF8("field2"); // 扩展字段2
        paramMap.put("field2", field2);
        String field3 = getString_UrlDecode_UTF8("field3"); // 扩展字段3
        paramMap.put("field3", field3);
        logger.info("代付结算,接收参数:{}", paramMap);
    	try {
	        RpUserPayConfig rpUserPayConfig = rpUserPayConfigService.getByPayKey(payKey);
	        if (rpUserPayConfig == null) {
	            throw new UserBizException(UserBizException.USER_PAY_CONFIG_ERRPR, "用户支付配置有误");
	        }
	        cnpPayService.checkIp(rpUserPayConfig, httpServletRequest);//ip校验
	        
	        if (!MerchantApiUtil.isRightSign(paramMap, rpUserPayConfig.getPaySecret(), sign)) {
	            throw new TradeBizException(TradeBizException.TRADE_ORDER_ERROR, "订单签名异常");
	        }

	        BigDecimal orderAmount = BigDecimal.valueOf(Double.valueOf(remitAmout));
            rpRemitManagerService.initRemitPay(rpUserPayConfig, orderNo, orderAmount, orderIp, bankAccountName, banAccountNo, remark, field1, field2, field3);
            resMap.put("apiCode", PublicEnum.YES.toString()); //默认成功
            resMap.put("apiMsg", "操作成功"); //默认成功
            resMap.put("sign", MerchantApiUtil.getSign(resMap, rpUserPayConfig.getPaySecret()));
		} catch (UserBizException e) {
        	logger.info(orderNo+"支付出现错误："+e.getMessage());
        	resMap.put("apiMsg", e.getMessage()); //默认成功
		}catch (Exception e) {
        	logger.info(orderNo+"支付出现异常:",e);
        	resMap.put("apiMsg", e.getMessage()); //默认成功
		}
        return resMap;
    }

    /**
     * 支付结果查询接口
     *
     * @param httpServletResponse
     */
    @RequestMapping("orderQuery")
    public void orderQuery(HttpServletResponse httpServletResponse) throws IOException {
    	Map<String, String> resMap = new HashMap<String, String>();
    	resMap.put("apiCode", PublicEnum.NO.toString()); //默认失败
    	resMap.put("apiMsg", "操作失败"); //默认失败
    	
    	Map<String, String> paramMap = new HashMap<String, String>();
        String payKey = getString_UrlDecode_UTF8("payKey"); // 企业支付KEY
        String orderNo = getString_UrlDecode_UTF8("orderNo"); // 订单号
        String sign = getString_UrlDecode_UTF8("sign"); // 签名
        paramMap.put("payKey", payKey);
        paramMap.put("orderNo", orderNo);

        try {
	        RpUserPayConfig rpUserPayConfig = rpUserPayConfigService.getByPayKey(payKey);
	        if (rpUserPayConfig == null) {
	            throw new UserBizException(UserBizException.USER_PAY_CONFIG_ERRPR, "用户支付配置有误");
	        }
	        if (!MerchantApiUtil.isRightSign(paramMap, rpUserPayConfig.getPaySecret(), sign)) {
	            throw new TradeBizException(TradeBizException.TRADE_ORDER_ERROR, "订单签名异常");
	        }
	        RpSettRecord payResult = rpRemitManagerService.getPayResult(rpUserPayConfig.getUserNo(), orderNo);
	        httpServletResponse.setContentType("text/text;charset=UTF-8");
	        resMap.put("apiCode", PublicEnum.YES.toString()); //默认成功
	        resMap.put("apiMsg", "操作成功"); //默认成功
	        resMap.put("orderStatus", payResult.getStatus()); //
	        resMap.put("orderAmount", payResult.getSettAmount().toString());
	        resMap.put("orderTime", payResult.getCreateTimeDesc()); 
	        resMap.put("sign", MerchantApiUtil.getSign(resMap, rpUserPayConfig.getPaySecret()));
		} catch (UserBizException e) {
        	logger.info(orderNo+"支付出现错误："+e.getMessage());
        	resMap.put("apiMsg", e.getMessage()); //默认成功
		}catch (Exception e) {
        	logger.info(orderNo+"支付出现异常:",e);
        	resMap.put("apiMsg", e.getMessage()); //默认成功
		}
        JsonUtils.responseJson(httpServletResponse, resMap);
    }

}
